<template>
  <div style="display:none"></div>
</template>

<script>

import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { devBaseURL } from '@/api'
import { getToken, getUser } from '@/utils/auth'
import { validatenull } from '@/utils/validate'

export default {
  data() {
    return {
      currentUser: validatenull(getUser()) ? null : JSON.parse(getUser()),
      stompClient: '',
      timer: ''
    }
  },
  methods: {
    gotoOrder() {
      this.$router.push({
        name: 'order'
      })
    },
    gotoUser() {
      this.$router.push({
        name: 'user'
      })
    },
    openNotice(obj) {

    },
    initWebSocket() {
      if (validatenull(this.currentUser)) { return }
      this.connection()
      const that = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send('test')
        } catch (err) {
          console.log('断线了: ' + err)
          that.connection()
        }
      }, 5000)
    },
    connection() {
      const socket = new SockJS(devBaseURL + 'notice-webSocket')
      this.stompClient = Stomp.over(socket)
      const headers = {
        'token': getToken(),
        'Content-Type': 'application/json;charset=UTF-8'
      }
      this.stompClient.connect(headers, () => {
        this.stompClient.subscribe('/user/' + this.currentUser.userId + '/message', (response) => {
          let gotoFunc
          if (validatenull(response)) { return }
          const obj = JSON.parse(response.body)
          if (obj.type === 'order') {
            gotoFunc = this.gotoOrder
          } else if (obj.type === 'user') {
            gotoFunc = this.gotoUser
          }
          const h = this.$createElement
          this.$notify.info({
            title: '新消息！',
            dangerouslyUseHTMLString: true,
            message: '<strong style="color: #409eff">' + obj.msg + '<br>点此跳转</strong>',
            onClick: gotoFunc,
            offset: 100,
            duration: 10000
          })
        })
      }, (err) => {
        console.log('失败')
        console.log(err)
      })
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    }
  },
  mounted() {
    this.initWebSocket()
  },
  beforeDestroy: function() {
    console.log('离开页面')
    this.disconnect()
    clearInterval(this.timer)
  }
}
</script>
